# -*- coding: utf-8 -*-
from decimal import Decimal, ROUND_UP
import json
import os
from pyquery import PyQuery
from requests.exceptions import ConnectionError
from export.b2b.b2b import B2b
from export.models import BaseProduct as Product, BaseProduct_Attr as Product_Attr, BaseProduct_B2b as Product_B2b,\
    BaseProduct_Price as Product_price, BaseProduct_Sku as ProductSku, BaseProduct_Stock as Product_Stock,\
    BaseProduct_Stock_Availability as Product_Stock_Availability, BaseProduct_Attr_Value as Product_Attr_Value
from settings import STATICFILES_DIRS

class Ugcontract(B2b):
    host = 'http://yugcontract.ua/'
    mainUrl = 'http://wholesale.yugcontract.ua/'
    loginUrl = 'http://wholesale.yugcontract.ua/wholesale/main.html'
    categoryUrl = 'wholesale/tree/?parent_id='

    stocksName = [['availability', 'Склад Киев'], ['availability_r2_0', 'Склад Винница']]
    stock = {}
    catalog={}

    username = 'KHazin_Marat'
    userpass = 'nm*@Za'

    def __init__(self):
        self.login()
        self.setCurrency()

    def getStockbyName(self, stockName):
        stock = Product_Stock.objects.get_or_create(stock_name=stockName, b2b=self.getUgcontract())
        return stock[0]


    def getProductsListUrl(self, categoryId):
        return 'wholesale/list/%s/fac-n/fpt-n/fsr-n/fst-n/fwh-n/l10000/sdir-desc/sort-model/?prop=0' % categoryId

    def getSearchProductUrl(self, query):
        return 'wholesale/list/search/l10000/sdir-desc/sort-model/?q=' + query

    def getUgcontract(self):
        b2b = Product_B2b.objects.get_or_create(b2b='ug-contract')
        return b2b[0]

    def setCurrency(self):
        self.browser.open(self.mainUrl)
        #        some time
        self.currency = 8.20

    def search(self, query, categoryName):
        result = json.loads(self.browser.open("%s%s" % (self.mainUrl, self.getSearchProductUrl(query))).get_data())
        if len(result['products']) == 1:
            return self.handlerHtmlProduct(result['products'][0], categoryName)


    def is_login(self, page):
        return self.mainUrl == page

    def setCategory(self, categoryId='0'):
        category = json.loads(self.browser.open(self.mainUrl + self.categoryUrl + categoryId).get_data(),
            encoding='utf-8')
        for category in category:
            if categoryId == '0':
                self.setCategory(category['id'])
            elif not category['have_children']:
                self.handlerHtmlCategory(category['id'], category['name'])
            elif category['id'].find(categoryId) != -1 and int(category['level']) == categoryId.count('_') + 1:
                self.setCategory(category['id'])


    def login(self):
        try:
            self.browser.open(self.mainUrl)
            if self.is_login(self.browser.geturl()):
                return True
            self.browser.select_form(nr=0)
            self.browser['user_login'] = self.username
            self.browser['user_password'] = self.userpass
            self.browser.submit()
            if self.is_login(self.browser.geturl()):
                return True
            else:
                return False
        except ConnectionError:
            return False

    def parsing(self):
        self.setCategory()

    def handlerHtmlCategory(self, categoryId, categoryName):
        products = json.loads(self.browser.open(self.mainUrl+self.getProductsListUrl(categoryId)).get_data(), encoding='utf-8')
        for product in products['products']:
            self.catalog[categoryName] = self.handlerHtmlProduct(product, categoryName)


    def handlerHtmlProduct(self, _product, categoryName):
        product = Product.objects.get(sku=_product['artikul'])
        if not product:
            product = Product.objects.get_or_create(brand_name=_product['brand'], sku=_product['artikul'],
            name='%s %s'%(_product['brand'], _product['name']), group=categoryName, description=_product['descr_typhoon'])
        else:
            product.brand_name=_product['brand']
            product.name='%s %s'%(_product['brand'], _product['name'])
            product.group=categoryName
            product.description=_product['descr_typhoon']
            product.save()
        productSku = ProductSku.objects.get_or_create(product=product, b2b=self.getUgcontract(),
            sku_b2b=_product['typhoon_id'])
        for stockName in self.stocksName:
            productAvailibility = Product_Stock_Availability.objects.get_or_create(product_id=product,
                stock_id=self.getStockbyName(stockName[1]), availability=_product[stockName[0]])
            del productAvailibility
        productPrice = Product_price.objects.get_or_create(sku=product, price_usd=Decimal(_product['price']),
            price_uah=Decimal(_product['price']).quantize(Decimal('.01'), rounding=ROUND_UP),
            b2b=self.getUgcontract())
        if _product['descr_url']:
            self.handlerHtmlProductAttribute(_product['descr_url'], product)
        return product

    def saveImage(self, productSku, listImage):
        for imageTag in listImage:
            self.browser.retrieve(self.host+imageTag.attrib['href'], os.path.join(STATICFILES_DIRS[0],'images/%s_%s.jpg'%(productSku, listImage.index(imageTag))))


    def handlerHtmlProductAttribute(self, link, product):
        jQuery = PyQuery(self.browser.open(link).get_data())
        self.saveImage(product.sku, jQuery('.block-photos a'))
        product.short_description=jQuery('.item-descr-small-content')[0].text_content().replace('\n','').strip()
        product.save()
        prop = jQuery('.prop')
        value = jQuery('.val')
        if len(prop) == len(value):
            for i in range(len(prop)):
                productAttr = Product_Attr.objects.get_or_create(attr_name=prop[i].text.replace('\n','').strip())
                productAttrValue = Product_Attr_Value.objects.get_or_create(sku=product,attr_value=value[i].text_content().replace('\n','').strip(),
                    attr=productAttr[0])
